package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    //引入静态化页面生成路径
    @Value("${out_put_path}")
    private String outputPath;

    /*分页查询*/
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        //定义三个参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //开启分页
        PageHelper.startPage(currentPage,pageSize);
        //调方法查询
        Page<CheckGroup> page =  setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());

    }

    //根据setmealId查询套餐
    //手机端根据套餐ID查询套餐详情（套餐基本信息、套餐对应的检查组信息、检查组对应的检查项信息）

   //这里引入检查组和检查项
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;

    //添加套餐(为移动端提供静态化页面生成技术)
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);

        Integer id = setmeal.getId();
        if(checkgroupIds!=null && checkgroupIds.length>0){
            //绑定套餐和检查组的多对多关系
            this.setSetmealAndCheckGroup(id,checkgroupIds);
        }
        //将图片名称保存到Redis
        String imgfilename = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgfilename);

        //生成静态页面
        generateMobileStaticHtml();

    }

    public void generateMobileStaticHtml(){
        //拿到套餐数据
        List<Setmeal> list = setmealDao.getAllSetmeal();
        //生成套餐列表页面
        generateMobileSetmealListHtml(list);
        //生成套餐详细信息页面(多个)
        generateMobileSetmealDetailHtml(list);

    }

    private void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map<String, Object> map = new HashMap<>();

        map.put("setmealList",list);
        //调用静态化页面(参数:页面模板名,生成的页面名,页面中显示的数据)
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);

    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map<String, Object> map = new HashMap<>();
            //查询详细套餐信息调用findById方法
            map.put("setmeal",this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }
        //静态化页面生成模板
    public void generateHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration(); //获得 配置对象
        Writer out =null;
        //加载模板文件
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outputPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try{
                if(null!=out){
                    out.flush();
                }
            }catch(Exception e2){
                e2.printStackTrace();
            }
        }

    }

    //移动端查询以及更新回显操作
    public Setmeal findById(Integer id) {
        //利用sql语句进行多表查询
         Setmeal setmeal = setmealDao.findById(id);

        //利用代码方法进行多表查询,遍历循环关联信息
        /*Setmeal setmeal =setmealDao.getById(id);  //这里仅仅之查出套餐里的数据,不含检查组
        List<CheckGroup> checkGroups = checkGroupDao.listBySetmealId(id);
        for (CheckGroup checkGroup : checkGroups) {
            List<CheckItem> checkItems =checkItemDao.findCheckItemByCheckGroudId(checkGroup.getId());
            checkGroup.setCheckItems(checkItems);
        }
        setmeal.setCheckGroups(checkGroups);*/
    return setmeal;
    }

    //根据套餐的id查询与检查组对应之间的关系,回显对应的关系
    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {

        return setmealDao.findCheckGroupIdsBySetmealId(setmealId);
    }

    //删除套餐
    @Override
    public void deleteByIdandimg(Integer id,String img) {

        //删除七牛云中图片
        QiniuUtils.deleteFileFromQiniu(img);

        //删除redis缓存中对应的的记录
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,img);
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);

        //检查当前删除的套餐与检查组是否关联
        //有关联的话,解除关联,因为检查组和检查项时多对多的关联关系id
        setmealDao.deleteBySetmealIDAndCheckGroupID(id);

        //解除关联后,再删除套餐
        setmealDao.deleteById(id);
    }

    //编辑套餐
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //删除原本的七牛云图片
        String img = setmeal.getImg();
        QiniuUtils.deleteFileFromQiniu(img);

        setmealDao.update(setmeal);
        //删除检查组和检查项的多对多的关联关系，操作t_checkgroup_checkitem表
        setmealDao.deleteBySetmealIDAndCheckGroupID(setmeal.getId());
        //得到检查组的id,重新建立相关联的关系
        Integer setmealId = setmeal.getId();
        //调用方法 在关联表中添加归属关系
        this.setSetmealAndCheckGroup(setmealId,checkgroupIds);
    }

    //查询每个套餐的订单数量
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //手机端查询全部套餐数据信息
    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.getAllSetmeal();
    }


    //设置关联表关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for(Integer checkgroupId: checkgroupIds){
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
